package handlers

import (
	"fmt"
	"html"
	"net/http"
	"net/url"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type GroupInviteHandler struct {
	db *gorm.DB
}

func NewGroupInviteHandler(db *gorm.DB) *GroupInviteHandler {
	return &GroupInviteHandler{db: db}
}

type createInviteLinkReq struct {
	GroupID       string `json:"groupId" binding:"required"`
	InviterUserID string `json:"inviterUserId"`
	InviteCode    string `json:"inviteCode"`
	LinkURL       string `json:"linkUrl" binding:"required"`
}

// 接收客户端提交的群邀请链接
func (h *GroupInviteHandler) CreateInviteLink(c *gin.Context) {
	var req createInviteLinkReq
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, errorResponse(400, "请求参数错误", err.Error()))
		return
	}

	// 不保存到数据库，直接根据请求体生成可访问的网页链接
	scheme := c.Request.Header.Get("X-Forwarded-Proto")
	if scheme == "" {
		if c.Request.TLS != nil {
			scheme = "https"
		} else {
			scheme = "http"
		}
	}
	host := c.Request.Host

	u := url.URL{
		Scheme: scheme,
		Host:   host,
		Path:   "/invite",
	}
	q := u.Query()
	q.Set("linkUrl", req.LinkURL)
	q.Set("groupId", req.GroupID)
	if req.InviterUserID != "" {
		q.Set("inviterUserId", req.InviterUserID)
	}
	if req.InviteCode != "" {
		q.Set("inviteCode", req.InviteCode)
	}
	u.RawQuery = q.Encode()
	pageURL := u.String()

	// 返回统一的 ApiResp 响应结构
	c.JSON(http.StatusCreated, successResponse(gin.H{
		"pageUrl": pageURL,
	}))
}

func (h *GroupInviteHandler) ShowInviteLandingPage(c *gin.Context) {
	// 从查询参数读取深度链接及元信息
	deepLink := c.Query("linkUrl")
	if deepLink == "" {
		c.String(http.StatusBadRequest, "缺少必要参数：linkUrl")
		return
	}
	groupID := c.Query("groupId")
	inviterUserID := c.Query("inviterUserId")
	inviteCode := c.Query("inviteCode")

	safeDeep := html.EscapeString(deepLink)

	meta := ""
	if groupID != "" || inviterUserID != "" {
		meta = fmt.Sprintf("群ID：%s | 邀请者：%s", html.EscapeString(groupID), html.EscapeString(inviterUserID))
		if inviteCode != "" {
			meta += " | 邀请码：" + html.EscapeString(inviteCode)
		}
	}

	htmlPage := `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>加入群聊</title>
<style>
body{font-family:system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;margin:24px;background:#f9fafb;color:#111827}
.card{background:#fff;border:1px solid #e5e7eb;border-radius:12px;padding:18px;max-width:640px;margin:0 auto}
h1{font-size:20px;margin:0 0 8px}
p{font-size:14px;color:#374151;margin:0 0 16px}
.btn{display:inline-block;background:#2563eb;color:#fff;padding:10px 16px;border-radius:8px;text-decoration:none}
.note{font-size:12px;color:#6b7280;margin-top:10px}
.link{word-break:break-all;color:#2563eb}
.meta{font-size:12px;color:#6b7280;margin-bottom:10px}
</style>
</head><body><div class="card">
<h1>邀请你加入 Paxiy 群聊</h1>
<div class="meta">` + meta + `</div>
<p>点击下方按钮，打开 Paxiy 并加入群聊。</p>
<p><a class="btn" id="openBtn" href="` + safeDeep + `">打开 Paxiy 加入群聊</a></p>
<p class="note">如果没有自动打开，请点击按钮或手动复制以下链接在支持的浏览器/设备打开：</p>
<p class="link">` + safeDeep + `</p>
</div>
<script>
(function(){
  var link = '` + safeDeep + `';
  // 尝试自动唤起
  setTimeout(function(){ window.location.href = link; }, 500);
})();
</script>
</body></html>`

	c.Header("Content-Type", "text/html; charset=utf-8")
	c.String(http.StatusOK, htmlPage)
}
